<template>
<div id="app">
  <add-data-comp @addData="addData" ></add-data-comp>
  <list-data-comp :datas="datas" @deleteData="deletData" @updateData="updateData"></list-data-comp>
  <operation-comp @searchData="searchData" :searchDatas="searchDatas"></operation-comp>
</div>
</template>

<script>
import AddDataComp from './components/AddData'
import ListDataComp from './components/ListData'
import OperationComp from './components/Operation'

const storeNames = 'Persons'

export default {
  name: 'App',
  data () {
    return {
      datas: [],
      maxId: 0,
      searchDatas: []
    }
  },
  components: {
    AddDataComp,
    ListDataComp,
    OperationComp
  },
  methods: {
    async addData (data) {
      // 父组件维护maxid
      data.id = ++this.maxId
      await this.db[storeNames].add(data).catch(err => {
        console.log(err.message)
      })
      this.datas.unshift(data)
    },
    async deletData (id) {
      // 从indexedDB中删除
      await this.db.Persons.remove(id).catch(err => {
        console.log(err)
      })
      this.datas.splice(this.datas.findIndex(item => item.id === id), 1)
      this.maxId = !this.datas.length ? 0 : this.maxId
    },
    async updateData (data) {
      await this.db.Persons.update(data).catch(err => {
        console.log(err)
      })
    },
    async searchData (name) {
      this.searchDatas = await this.db.Persons.readWithIndex(name).catch(err => {
        console.log(err)
      })
    }
  },
  async mounted () {
    // TODO: 这里要想办法解决了!!!!
    setTimeout(async () => {
      this.datas = await this.db.Persons.readAll().catch(err => {
        console.log(err)
      }) || []

      this.maxId = this.datas[this.datas.length - 1].id
    }, 2000)
  }
}
</script>
